<template>
  <div class="chapter-content">
    <div class="main">
      <!-- 左侧内容区 -->
      <div class="left" ref="leftContent" @scroll="onScroll">
        <div class="title">
          <h1>{{ Chapter.title }}</h1>
          <h5 class="time">更新日期：{{ formatDate(Chapter.create_time) }}</h5>
        </div>
        <div class="content" v-html="Chapter.content"></div>
        <el-divider></el-divider>
<!--        <span>未能解决你的问题？请联系 <el-link type="primary">在线客服</el-link></span>-->
        <div class="footer">
          <div class="footer-right" v-if="previousChapter.id" @click="pervious">
            <el-link type="primary" >上一篇</el-link>
            <h3>{{previousChapter.title}}</h3>
          </div>
          <div class="footer-left" v-if="nextChapter.id" @click="next">
            <el-link type="primary"  >下一篇</el-link>
            <h3>{{ nextChapter.title }}</h3>
          </div>

        </div>
      </div>

      <!-- 右侧标题区 -->
      <div class="right">
        <ul>
          <!-- 遍历标题，添加点击事件 -->
          <li v-for="(title, index) in titles" :key="index"
              :class="{ active: activeIndex === index }"
              @click="scrollToTitle(index)">
            {{ title }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { getChapter } from "@/api/helpDocument";
import {isArray} from "lodash";

export default {
  name: 'Chapter',
  props: ['selectId'],
  data() {
    return {
      Chapter: {},           // 存储章节数据
      titles: [],            // 存储提取的标题
      activeIndex: 0,        // 当前高亮的标题索引
      headerElements: [],     // 存储标题元素的数组
      nextChapter:{},
      previousChapter:{},
    };
  },
  mounted() {
    this.init();  // 初始化章节数据
    this.$nextTick(() => {
      this.extractTitles(); // 提取标题及其元素
    });
  },
  watch: {
    selectId(newVal) {
      this.init(); // selectId 变化时重新初始化数据
    },
    Chapter(newVal) {
      this.$nextTick(() => {
        this.extractTitles(); // 章节数据变化时重新提取标题
      });
    }
  },
  methods: {
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toISOString().split('T')[0];
    },
    pervious() {
      this.$emit('page-clicked', this.previousChapter.id); // 触发自定义事件
    },
    next() {
      this.$emit('page-clicked', this.nextChapter.id); // 触发自定义事件
    },
    // 初始化章节数据
    init() {
      if (this.selectId) {
        getChapter({id: this.selectId,system_type:0}).then((res) => {
          this.Chapter = res.data;
          if (res.info && res.info.nextChapter) {
            this.nextChapter = res.info.nextChapter;
          } else {
            this.nextChapter = {}; // Default to empty object or handle as needed
          }
          if (res.info && res.info.previousChapter) {
            this.previousChapter = res.info.previousChapter;
          } else {
            this.previousChapter = {}; // Default to empty object or handle as needed
          }
          this.$nextTick(() => {
            this.extractTitles(); // 数据加载后提取标题
          });
        });
      } else {
        getChapter({id: 0, type: 0, isInit: true,system_type:0}).then((res) => {
          this.Chapter = res.data;
          if (res.info && res.info.nextChapter) {
            this.nextChapter = res.info.nextChapter;
          } else {
            this.nextChapter = {}; // Default to empty object or handle as needed
          }
          if (res.info && res.info.previousChapter) {
            this.previousChapter = res.info.previousChapter;
          } else {
            this.previousChapter = {}; // Default to empty object or handle as needed
          }
          this.$nextTick(() => {
            this.extractTitles(); // 数据加载后提取标题
          });
        });
      }
    },
    // 提取标题及其元素
    extractTitles() {
      const contentElement = this.$refs.leftContent.querySelector('.content');
      if (contentElement) {
        this.headerElements = Array.from(contentElement.querySelectorAll('h1, h2, h3'));
        this.titles = this.headerElements.map(el => el.innerText);
      }
    },
    // 滚动到指定标题的位置
    scrollToTitle(index) {
      const element = this.headerElements[index];
      if (element) {
        this.$refs.leftContent.scrollTo({
          top: element.offsetTop,
          behavior: 'smooth'
        });

        // 确保 activeIndex 更新在滚动完成后
        this.$nextTick(() => {
          this.activeIndex = index;
        });
      }
    },
    // 根据滚动位置更新当前高亮的标题
    onScroll() {
      const contentElement = this.$refs.leftContent;
      const scrollTop = contentElement.scrollTop;
      const viewportHeight = contentElement.clientHeight;

      let newActiveIndex = this.headerElements.length - 1; // Start with the last header by default
      let closestDistance = Infinity;

      this.headerElements.forEach((header, index) => {
        const headerTop = header.offsetTop;
        const headerBottom = headerTop + header.offsetHeight;

        // Check if the header is fully visible or partially visible in the viewport
        if ((headerTop >= scrollTop && headerTop <= (scrollTop + viewportHeight)) ||
          (headerBottom >= scrollTop && headerBottom <= (scrollTop + viewportHeight))) {
          const distance = Math.min(
            Math.abs(headerTop - scrollTop),
            Math.abs(headerBottom - scrollTop),
          );

          if (distance < closestDistance) {
            closestDistance = distance;
            newActiveIndex = index;
          }
        }
      });

      if (newActiveIndex !== this.activeIndex) {
        this.activeIndex = newActiveIndex;
      }
    }

  }
}
</script>

<style scoped lang="scss">
.chapter-content {
  display: flex;
  height: 100vh; /* 确保容器占满视口高度 */
  flex-direction: column;

  .main {
    display: flex;

    .left {
      overflow-x: hidden; /* 允许内容滚动 */

      overflow-y: auto; /* 允许内容滚动 */
      width: 80%;
      border-right: 1px solid #ccc;
      height: calc(100vh - 70px); /* 视口高度减去 header 高度 */
      position: relative; /* 允许定位右侧标题 */

      .title {
        position: relative;
        margin-right: 30px;

        .time {
          position: absolute;
          right: 0; /* 将 h5 定位到右边 */
          bottom: -20px; /* 根据需要调整距离 h1 的垂直位置 */
          margin: 0; /* 移除默认的 margin */

        }

      }

      .content {
        border-top: 1px solid #ccc;
        margin-right: 30px;

      }

      .footer {
        //display: flex;
        position: relative;
        //justify-content: space-between;
        margin-top: 180px;
        margin-bottom: 420px;
        margin-right: 20px;
      }
      .footer-left {
        position: absolute;
        right: 0; /* 将 h5 定位到右边 */
        margin: 0; /* 移除默认的 margin */
      }
      .footer-right {
        position: absolute;
        left: 0; /* 将 h5 定位到右边 */
        margin: 0; /* 移除默认的 margin */
      }

    }

    .right {
      width: 20%;
      border-left: 1px solid #ccc;
      height: calc(100vh - 10px); /* 视口高度减去 header 高度 */
      overflow-y: auto; /* 允许内容滚动 */
      position: sticky;
      top: 0; /* 保持在顶部 */
      background: white;

      ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          padding: 10px;
          cursor: pointer;
          transition: background 0.3s;
          color: gray;
          &.active {
            background: white;
            font-weight: bold;
            color: black;
          }

          &:hover {
            background: #eee;
          }
        }
      }
    }
  }

  /* Webkit 浏览器滚动条样式 */
  ::-webkit-scrollbar {
    width: 2px; /* 滚动条宽度 */
  }

  ::-webkit-scrollbar-thumb {
    background: #888; /* 滚动条颜色 */
    border-radius: 10px; /* 圆角 */
  }

  ::-webkit-scrollbar-thumb:hover {
    background: #555; /* 鼠标悬停时滚动条颜色 */
  }
}
::v-deep img {
  border-style: none;
  max-width: 100%;
  height: auto;
}
</style>
